#coding:utf-8
from PIL import Image
import urllib
import re
import sys
import time
import os
import uuid
import MySQLdb

def add_mysql(val):
     # 打开数据库连接
    db = MySQLdb.connect("localhost","root","root","xuexi" )
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()
    cursor.execute("SET NAMES utf8")
    try:
       cursor.executemany("INSERT INTO song_images(u_id, type_id, title, content, compress_url, raw_url, sort, addtime, happen_time, is_activity) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)", val)
       db.commit()
    except:
       db.rollback()
    db.close()

def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html

def save_to_file(name, contents):
    f = open(name, "w")
    f.write(contents)
    f.close()
def resize_img(img_path,name):
  try:
    img = Image.open(img_path)
    (width,height) = img.size
    new_width = 200
    # new_height = height * new_width / width
    new_height = 200
    out = img.resize((new_width,new_height),Image.ANTIALIAS)
    ext = os.path.splitext(img_path)[1]
    new_file_name = '%s%s' %(name+'-small',ext)
    out.save(new_file_name,quality=95)
  except Exception,e:
    print e

   
def getImg(html,path,uid):
    imgnamearr = []
    reg = r'src="(.*?\.jpg)" 'r'src="([^>]+\.jpg'
    #reg = r'class="BDE_Image" src="(.+?\.jpg)"'
    imgre = re.compile(reg)
    imglist = re.findall(imgre,html)
    # return imglist
    #循环把图片存到本地
    x = 0
    sql_val =[]
   
    for imgurl in imglist:
        #保存到本地
        # img_url = path+'\\%s.jpg' % x
        img_url = path+'/'+str(uuid.uuid1())+str(x)+'.jpg'
        urllib.urlretrieve(imgurl,img_url)
        _url = img_url.split('/')
        #生成一个压缩图片
        # name_all = _url[6].split('.')
        # name_all = _url[4].split('.')
        # resize_img(img_url, path+'/'+name_all[0])
        tmp =[]
        tmp.append(uid)
        tmp.append(0)
        tmp.append(0)
        tmp.append('同步的图片')
        # tmp.append('/image/'+str(time.strftime('%Y-%m-%d',time.localtime(time.time())))+'/'+name_all[0]+'-small.'.+name_all[1])
        tmp.append('/image/'+str(time.strftime('%Y-%m-%d',time.localtime(time.time())))+'/'+_url[4])
        #tmp.append('/image/'+str(time.strftime('%Y-%m-%d',time.localtime(time.time())))+'/'+_url[6])
        # tmp.append('/image/'+str(time.strftime('%Y-%m-%d',time.localtime(time.time())))+'/'+name_all[0]+'-small.jpg')
        tmp.append('/image/'+str(time.strftime('%Y-%m-%d',time.localtime(time.time())))+'/'+_url[4])
        tmp.append(0)
        tmp.append( time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) )
        tmp.append( time.strftime('%Y-%m-%d',time.localtime(time.time())))
        tmp.append(1)
        sql_val.append(tmp)
        imgnamearr.append(str(uuid.uuid1())+str(x)+'.jpg')
        x+=1
    return sql_val    
    # return imgnamearr

 # print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))  /usr/local/lib/python2.7/site-packages/PIL 
# print sys.argv[1]
# print sys.argv[1][0:] http://tieba.baidu.com/p/2460150866
 # exit()
# sys.exit() http://tieba.baidu.com/f?kw=%E5%9B%BE%E7%89%87&tab=album
url = sys.argv[1][0:]
uid = sys.argv[2][0:]
html = getHtml(url)
nowdate = time.strftime('%Y-%m-%d',time.localtime(time.time()))
path =  sys.path[0]
url2 = path+'/Public/image/'+nowdate
if not os.path.exists(url2):   
   os.makedirs(url2,0777) 
arr = getImg(html,url2,uid)
print arr
sys.exit()
print(add_mysql(arr))


# save_to_file('html.html',html);
# print html